import { login, getInfo } from '@/api/user'
import { getAccessToken, setAccessToken, removeAccessToken, getRefreshToken, setRefreshToken, removeRefreshToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    accessToken: getAccessToken(),
    refreshToken: getRefreshToken(),
    userName: '',
    realName: '',
    avatar: '',
    gender: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ACCESS_TOKEN: (state, accessToken) => {
    state.accessToken = accessToken
  },
  SET_REFRESH_TOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_REALNAME: (state, realName) => {
    state.realName = realName
  },
  SET_USERNAME: (state, userName) => {
    state.userName = userName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_Gender: (state, gender) => {
    state.gender = gender
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { userName, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: userName.trim(), password: password }).then(data => {
        commit('SET_ACCESS_TOKEN', data.accessToken)
        commit('SET_REFRESH_TOKEN', data.refreshToken)

        setAccessToken(data.accessToken)
        setRefreshToken(data.refreshToken)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(data => {
        const { realName, gender, userName, avatar } = data

        commit('SET_REALNAME', realName)
        commit('SET_USERNAME', userName)
        commit('SET_AVATAR', avatar)
        commit('SET_Gender', gender)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeAccessToken()
      removeRefreshToken()
      
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeAccessToken()
      removeRefreshToken()

      commit('RESET_STATE')
      resolve()
    })
  },
  
  setToken({ commit }, data) {
    return new Promise(resolve => {
      const { accessToken, refreshToken } = data

      commit('SET_ACCESS_TOKEN', accessToken)
      commit('SET_REFRESH_TOKEN', refreshToken)

      setAccessToken(accessToken)
      setRefreshToken(refreshToken)
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

